package com.mgface.zookeeper.curator.function;

import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

public class 子节点事件监听 {

	public static void main(String[] args) throws Exception {
		CuratorFramework client = CuratorFrameworkFactory.builder().connectString("localhost:2181")
				.sessionTimeoutMs(10_000).connectionTimeoutMs(10_000).retryPolicy(new ExponentialBackoffRetry(1000, 3))
				.build();
		client.start();
		System.out.println("连接启动完毕");
		String path = "/zk-book";
		client.delete().deletingChildrenIfNeeded().forPath(path);
		PathChildrenCache cache = new PathChildrenCache(client, path, true);
		cache.start(StartMode.POST_INITIALIZED_EVENT);
		
		cache.getListenable().addListener((clent, event) -> {
			switch (event.getType()) {
			case CHILD_ADDED:
				System.out.println("child_add:"+event.getData().getPath());
				break;
			case CHILD_REMOVED:
				System.out.println("child_removed:"+event.getData().getPath());
				break;
			case CHILD_UPDATED:
				System.out.println("child_updated:"+event.getData().getPath());
				break;
			default:
				break;
			}
		});
		
		client.create().withMode(CreateMode.PERSISTENT).forPath(path);
		TimeUnit.SECONDS.sleep(1);
		client.create().withMode(CreateMode.PERSISTENT).forPath(path+"/c1");
		client.create().withMode(CreateMode.PERSISTENT).forPath(path+"/c2");
		TimeUnit.SECONDS.sleep(1);
		client.delete().deletingChildrenIfNeeded().forPath(path+"/c1");
		TimeUnit.SECONDS.sleep(1);
		client.delete().deletingChildrenIfNeeded().forPath(path);
		cache.close();
	}

}
